//蓝牙控制层
const util = require("../../utils/util");
const app = getApp();
//蓝牙适配
class BLEAdapter{
  constructor(){
  }
  //开启适配器
  openBluetoothAdapter(){
    wx.openBluetoothAdapter({
      seuucess:function (res){}
    })
  }
  //开始扫描
  startScan() {
    wx.openBluetoothAdapter()
    wx.startBluetoothDevicesDiscovery({
      success: () => {
        console.log('开始扫描')
        wx.onBluetoothAdapterStateChange(res => {
          if(res.discovering) {
            this.onDiscovering()  
          }
        })
      }
    })
  }
    //扫描到设备
    onDiscovering() {
      wx.getBluetoothDevices({
        success: (res) => {
          console.log('扫描到设备:')
          this.devices = res.devices.map(item => {
            return new BLEDevice(item)
          })
          // 处理结果
          this.onDeviceScanned(this.devices)  
        }
      })
    } 
     //适配状态获取
  getAdapterState(callback) {
    wx.getBluetoothAdapterState({
       success: res => {
         callback(res);
       } 
    });
  }
  //异常重启适配器
  getTheAdapterRestart() {
      wx.closeBluetoothAdapter({
        success: () => {
          this.onBluetoothAdapterStateChange(() => {
            if (!this.available) {
              wx.openBluetoothAdapter() 
            }
          })
        }
      })
  }
    //停止扫描
  stopScan() {
    wx.stopBluetoothDevicesDiscovery() 
}
    //关闭适配
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter();
}
}
//蓝牙连接
class BLEConnection{
  constructor(){
    this.deviceId=''
  }
  //设备回调连接
    connect(deviceId,callback) {
      wx.createBLEConnection({
        deviceId,
        success:()=>{
          callback(deviceId)
        },
        fail:()=>{
          callback(null)
        }
      })
    }
  //成功连接
  connectSuccess(toConnectedDeviceId) {
    var that = this;
    app.globalData.connectedDeviceId = toConnectedDeviceId;
    setTimeout(() => {
    }, 500);
  }
}
class BLEService{
  constructor() {
    this.deviceId = ""
    this.serviceId = ""
    this.characteristicId= ""
  }
  //获取蓝牙特征值
  getCharacteristics(serviceId, callback) {
      wx.getBLEDeviceCharacteristics({
        deviceId: this.deviceId,
        serviceId,
        success: res => {
          callback(res);
          if (item.properties.write) {
            _deviceId = deviceId;
            _serviceId = serviceId;
            _characteristicId = item.uuid;
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            });
          }
      }
      });
    }
    //获取设备服务
  getBLEDeviceServices(deviceId, callback) {
    this.deviceId = deviceId;
    wx.getBLEDeviceServices({
      deviceId,
      success: res => {
        monitorTheBlue();
        getTheBlueDisConnectWithAccident();
        callback(res);
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
            return;
          }
        }
      } 
    });
  }
  //读取设备特征值
  readCharacteristic(serviceId, characteristicId) {
    const adapter=wx.getBluetoothAdapter();
    const device=adapter.getDevice(deviceId);
    device.connect();
    device.onConnected(()=>{
    wx.readBLECharacteristicValue({
      deviceId: this.deviceId,
      serviceId,
      characteristicId,
      success:res=>{
        const data=res.data;//数据定义
        device.disconnect();//断联  
        callback(data);//数据返回
      }
    });
  })
    device.onDisconnected(() => {
  wx.offBLECharacteristicValueChange();//关闭特征值变化监听
  device.off('error'); //error监听关闭
  device = null;//device对象值变为null
});
  }
 
  //特征变化回调
  onCharacteristicChange(callback) {
    wx.onBLECharacteristicValueChange(res => {
      const data=res.data;
      callback(res.data);
    });
  }
} 

  
 
module.exports={
  BLEAdapter,
  BLEService,
  BLEConnection
}